package org.example.springcloud.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.example.springcloud.callback.DBPasswordCallback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.sql.SQLException;

@Configuration
@RefreshScope
public class DataSourceConfig {

    @Autowired
    private DataSourceProperties properties;

    @Bean
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setPasswordCallback(new DBPasswordCallback());
        dataSource.setUrl(properties.getUrl());
        dataSource.setUsername(properties.getUsername());
        //获取密码服务密码
        dataSource.setPassword(properties.getPassword());
        dataSource.setDriverClassName(properties.getDriverClassName());
        try {
            dataSource.init();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return dataSource;
    }
}
